package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"xiao-hong-dev/cache"
	"xiao-hong-dev/model"
	"xiao-hong-dev/pkg"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "参数不能为空",
		})
		return
	}
	redis_Key := "login_error_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_Key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次,禁止登录",
		})
		return
	}

	//判断用户是否存在
	var user model.User
	err := model.DB.Debug().Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	//判断密码是否正确
	if user.Password != pkg.Md5str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_Key) //密码错误一次加一
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_Key, 3, time.Second*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次,封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size

	var user []*model.User
	redis_key := "user_list_page_" + strconv.Itoa(page)
	cacheDate, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheDate == "" {
		model.DB.Offset(offset).Limit(size).Order("id asc").Find(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	} else {
		json.Unmarshal([]byte(cacheDate), &user)
	}
	var total int64
	model.DB.Model(&user).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "Ok",
		"data":  user,
		"total": total,
	})
	return

}
